<template>
  <div class="payment-page">
    <van-nav-bar title="支付" left-arrow @click-left="onBack" fixed />

    <div class="content">
      <!-- 支付信息卡片 -->
      <div class="payment-info-card">
       
        
        <div class="info-item">
          <span class="info-label">科室</span>
          <span class="info-value">{{ paymentData.departmentName }}</span>
        </div>
        
        <div class="info-item">
          <span class="info-label">医生</span>
          <span class="info-value">{{ paymentData.doctorName }}</span>
        </div>
        
        <div class="info-item">
          <span class="info-label">日期</span>
          <span class="info-value">{{ formatTime(paymentData.operatingTime) }}</span>
        </div>
        
        <div class="info-item highlight">
          <span class="info-label">支付金额</span>
          <span class="info-value amount">¥{{ paymentData.paymentAmount }}</span>
        </div>
      </div>

      <!-- 卡内余额 -->
      <div class="balance-info">
        <span class="balance-label">卡内余额</span>
        <span class="balance-value">¥{{ paymentData.balance }}</span>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <h3 class="method-title">选择支付方式</h3>
        
        <van-radio-group v-model="selectedPaymentMethod">
          <div 
            class="method-item"
            v-for="method in paymentMethods"
            :key="method.value"
            @click="selectedPaymentMethod = method.value"
          >
            <div class="method-info">
              <van-icon :name="method.icon" size="24" :color="method.color" />
              <span class="method-name">{{ method.label }}</span>
            </div>
            <van-radio :name="method.value" />
          </div>
        </van-radio-group>
      </div>

      <!-- 支付按钮 -->
      <div class="payment-footer">
        <van-button 
          type="primary" 
          size="large" 
          round
          block
          @click="handleConfirmPayment"
          :loading="paying"
        >
          确认支付 ¥{{ paymentData.paymentAmount }}
        </van-button>
      </div>
    </div>

    <van-tabbar v-model="activeTab" fixed>
      <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
      <van-tabbar-item icon="contact" to="/profile">个人中心</van-tabbar-item>
    </van-tabbar>

    <!-- 订单信息弹窗 -->
    <van-popup 
      v-model:show="showOrderInfo" 
      position="center" 
      :round="true"
      :close-on-click-overlay="false"
      :style="{ width: '90%', maxWidth: '400px' }"
    >
      <div class="order-info-popup">
        <div class="popup-header">
          <van-icon name="success" color="#07c160" size="40" />
          <h3 class="popup-title">支付成功</h3>
        </div>
        
        <div class="order-details">
          <div class="detail-item">
            <span class="detail-label">订单编号(AmountId)</span>
            <span class="detail-value">{{ orderInfo.amountId }}</span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">支付金额</span>
            <span class="detail-value amount">¥{{ orderInfo.paymentAmount }}</span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">支付方式</span>
            <span class="detail-value">{{ orderInfo.paymentMethod }}</span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">支付时间</span>
            <span class="detail-value">{{ orderInfo.paymentTime }}</span>
          </div>
          
          <div class="detail-item">
            <span class="detail-label">支付状态</span>
            <span class="detail-value status-success">{{ orderInfo.status }}</span>
          </div>
          
          <div class="detail-item" v-if="orderInfo.description">
            <span class="detail-label">说明</span>
            <span class="detail-value">{{ orderInfo.description }}</span>
          </div>
        </div>
        
        <div class="popup-footer">
          <van-button 
            type="primary" 
            size="large" 
            round
            block
            @click="closeOrderInfo"
          >
            完成
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { api, type Patient } from '@/api'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const activeTab = ref(0)
const paying = ref(false)
const showOrderInfo = ref(false)
const orderInfo = ref({
  amountId: '',
  paymentAmount: '',
  paymentTime: '',
  paymentMethod: '',
  status: '',
  description: ''
})

// 支付数据
interface PaymentData {
  // 基础信息
  amountId: number
  operatingNum: string
  source: string
  paymentMethod: number
  paymentStatus: string
  
  // 金额信息
  paymentAmount: string
  balance: string
  
  // 费用类型
  expenseId: string
  expenseName: string
  
  // 科室和医生信息
  departmentId: string
  departmentName: string
  doctorName: string
  
  // 时间信息
  operatingTime: string
  
  // 就诊人信息
  patientId: string
  name: string
  medicalCard: string
  
  // 其他信息
  businessId: string
  businessName: string
  appointmentId: string
}

const paymentData = ref<PaymentData>({
  // 基础信息
  amountId: 0,
  operatingNum: '',
  source: '',
  paymentMethod: 0,
  paymentStatus: '',
  
  // 金额信息
  paymentAmount: '0.00',
  balance: '0.00',
  
  // 费用类型
  expenseId: '',
  expenseName: '',
  
  // 科室和医生信息
  departmentId: '',
  departmentName: '',
  doctorName: '',
  
  // 时间信息
  operatingTime: '',
  
  // 就诊人信息
  patientId: '',
  name: '',
  medicalCard: '',
  
  // 其他信息
  businessId: '',
  businessName: '',
  appointmentId: ''
})

// 支付方式
const selectedPaymentMethod = ref('wechat')
const paymentMethods = [
  { label: '微信支付', value: 'wechat', icon: 'chat-o', color: '#07c160' },
  { label: '支付宝', value: 'alipay', icon: 'shield-o', color: '#1677ff' },
  { label: '卡内余额', value: 'balance', icon: 'balance-o', color: '#ff976a' }
]

// 返回
const onBack = () => {
  router.back()
}

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  try {
    // 处理 ISO 格式时间：2025-10-16T15:23:31
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    // 如果时间格式不正确，返回原字符串
    return timeStr
  }
}

// 关闭订单信息弹窗
const closeOrderInfo = () => {
  showOrderInfo.value = false
  // 关闭后跳转到首页
  setTimeout(() => {
    router.push('/')
  }, 300)
}

// 支付订单 - 使用 axios (基于 Alipay PagePay 接口)
const PayOrder = (info: any) => {
  // 使用实际的API地址，根据您的后端配置
  const apiUrl = 'http://localhost:5103/api/Alipay/PagePay'
  
  return axios.post(apiUrl, null, {
    params: {
      AmountId: info.Order_SnowId,
      PaymentAmount: info.Order_Money
    }
  })
  .then(res => {
    if (res.status === 200) {
      // 支付宝 PagePay 通常返回 HTML 表单
      return res.data
    }
    throw new Error('支付请求失败')
  })
  .catch(error => {
    console.error('支付订单错误:', error)
    throw error
  })
}

// 确认支付
const handleConfirmPayment = async () => {
  try {
    // 验证必需字段
    if (!paymentData.value.amountId || paymentData.value.amountId === 0 || isNaN(paymentData.value.amountId)) {
      Toast.fail('支付信息不完整，请重新选择待缴费项目')
      console.error('AmountId无效:', paymentData.value.amountId, '类型:', typeof paymentData.value.amountId)
      return
    }

    // 验证支付金额
    const paymentAmount = parseFloat(paymentData.value.paymentAmount)
    if (isNaN(paymentAmount) || paymentAmount <= 0) {
      Toast.fail('支付金额无效')
      return
    }

    // 如果选择卡内余额支付，检查余额是否充足
    if (selectedPaymentMethod.value === 'balance') {
      const currentBalance = parseFloat(paymentData.value.balance)
      if (isNaN(currentBalance) || currentBalance < paymentAmount) {
        Toast.fail('卡内余额不足，请选择其他支付方式')
        return
      }
    }

    const methodLabel = paymentMethods.find(m => m.value === selectedPaymentMethod.value)?.label || '当前支付方式'
    
    // 确认支付
    await Dialog.confirm({
      title: '确认支付',
      message: `确定使用${methodLabel}支付 ¥${paymentData.value.paymentAmount} 吗？`,
    })

    paying.value = true

    console.log('发送支付请求，参数:', {
      Order_SnowId: paymentData.value.amountId,
      Order_Money: paymentAmount
    })

    // 显示加载提示
    Toast.loading({
      message: '支付处理中...',
      forbidClick: true,
      duration: 0
    })

    // 调用支付接口 - 使用 axios
    const response = await PayOrder({
      Order_SnowId: paymentData.value.amountId,
      Order_Money: paymentAmount
    })

    console.log('支付接口响应:', response)

    // 检查响应 - 如果返回的是 HTML 字符串（支付宝表单），则写入到 document
    if (response && typeof response === 'string' && response.includes('form')) {
      // 将支付宝返回的表单写入页面，自动提交
      document.write(response)
      return // 跳转到支付宝页面，后续流程由支付宝处理
    }

    Toast.clear()

    // 生成订单信息
    const currentTime = new Date()
    
    // 从API响应或请求数据获取信息
    const apiAmountId = paymentData.value.amountId
    const apiPaymentAmount = paymentAmount
    
    // 计算显示说明
    let orderDescription = ''
    if (selectedPaymentMethod.value === 'balance') {
      const currentBalance = parseFloat(paymentData.value.balance)
      const remainingBalance = currentBalance - paymentAmount
      orderDescription = `卡内余额支付，余额剩余 ¥${remainingBalance.toFixed(2)}`
    } else {
      orderDescription = `${methodLabel}支付成功`
    }
    
    // 填充订单信息
    orderInfo.value = {
      amountId: String(apiAmountId),
      paymentAmount: Number(apiPaymentAmount).toFixed(2),
      paymentTime: currentTime.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-'),
      paymentMethod: methodLabel,
      status: '支付成功',
      description: orderDescription
    }

    Toast.success('支付成功')
    
    // 显示订单信息弹窗
    setTimeout(() => {
      showOrderInfo.value = true
    }, 500)

  } catch (error) {
    Toast.clear() // 清除加载提示
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      const errorMessage = error instanceof Error ? error.message : '支付失败，请重试'
      Toast.fail(errorMessage)
    }
  } finally {
    paying.value = false
  }
}

// 页面加载时从路由获取数据
onMounted(() => {
  if (route.query) {
    paymentData.value = {
      // 基础信息
      amountId: route.query.amountId ? Number(route.query.amountId) : 0,
      operatingNum: (route.query.operatingNum as string) || '',
      source: (route.query.source as string) || '',
      paymentMethod: Number(route.query.paymentMethod) || 0,
      paymentStatus: (route.query.paymentStatus as string) || '',
      
      // 金额信息
      paymentAmount: (route.query.paymentAmount as string) || '0.00',
      balance: (route.query.balance as string) || '0.00',
      
      // 费用类型
      expenseId: (route.query.expenseId as string) || '',
      expenseName: (route.query.expenseName as string) || '',
      
      // 科室和医生信息
      departmentId: (route.query.departmentId as string) || '',
      departmentName: (route.query.departmentName as string) || '',
      doctorName: (route.query.doctorName as string) || '',
      
      // 时间信息
      operatingTime: (route.query.operatingTime as string) || '',
      
      // 就诊人信息
      patientId: (route.query.patientId as string) || '',
      name: (route.query.name as string) || '',
      medicalCard: (route.query.medicalCard as string) || '',
      
      // 其他信息
      businessId: (route.query.businessId as string) || '',
      businessName: (route.query.businessName as string) || '',
      appointmentId: (route.query.appointmentId as string) || ''
    }
    
    console.log('接收到的支付数据:', paymentData.value)
    console.log('路由参数 amountId:', route.query.amountId, '类型:', typeof route.query.amountId)
  }
})
</script>

<style scoped>
.payment-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.content {
  width: 100%;
  max-width: 480px;
  margin: 0 auto;
  padding-top: calc(46px + env(safe-area-inset-top, 0px));
  padding-left: 16px;
  padding-right: 16px;
  padding-bottom: calc(140px + env(safe-area-inset-bottom, 0px));
  box-sizing: border-box;
}

/* 支付信息卡片 */
.payment-info-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f7f8fa;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item.highlight {
  padding: 16px 0;
  margin-top: 8px;
  border-top: 1px solid #ebedf0;
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #969799;
}

.info-value {
  font-size: 14px;
  color: #323233;
  font-weight: 500;
}

.info-value.amount {
  font-size: 24px;
  color: #ee0a24;
  font-weight: 600;
}

/* 卡内余额 */
.balance-info {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.balance-label {
  font-size: 14px;
  color: #969799;
}

.balance-value {
  font-size: 18px;
  color: #323233;
  font-weight: 600;
}

/* 支付方式 */
.payment-methods {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.method-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin: 0 0 16px 0;
}

.method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  cursor: pointer;
  border-bottom: 1px solid #f7f8fa;
}

.method-item:last-child {
  border-bottom: none;
}

.method-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.method-name {
  font-size: 15px;
  color: #323233;
}

/* 支付按钮 */
.payment-footer {
  position: fixed;
  bottom: calc(50px + env(safe-area-inset-bottom, 0px));
  left: 0;
  right: 0;
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #ebedf0;
  z-index: 100;
}

.payment-footer .van-button {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #1989fa 0%, #1976d2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
}

.payment-footer .van-button:active {
  opacity: 0.8;
}

/* 响应式适配 */
@media (min-width: 480px) and (max-width: 768px) {
  .content {
    max-width: 520px;
  }
  
  .payment-footer {
    max-width: 520px;
    left: 50%;
    transform: translateX(-50%);
  }
}

/* 订单信息弹窗样式 */
.order-info-popup {
  padding: 24px;
  text-align: center;
}

.popup-header {
  margin-bottom: 24px;
}

.popup-title {
  font-size: 20px;
  font-weight: 600;
  color: #323233;
  margin: 12px 0 0 0;
}

.order-details {
  margin-bottom: 24px;
  text-align: left;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 14px;
  color: #646566;
  font-weight: 500;
}

.detail-value {
  font-size: 14px;
  color: #323233;
  font-weight: 600;
  text-align: right;
  max-width: 60%;
  word-break: break-all;
}

.detail-value.amount {
  color: #ee0a24;
  font-size: 16px;
  white-space: normal;
  line-height: 1.4;
}

.detail-value.status-success {
  color: #07c160;
}

.popup-footer {
  margin-top: 8px;
}
</style>

